package eg.backend.util;

import java.util.List;

import eg.backend.domain.Dimension;
import eg.backend.query.AggregateSO;
import eg.backend.query.QueryDefinition;

public class Converter {
	public static AggregateSO toAggregateSO(final QueryDefinition queryDefinition) {
		AggregateSO so = new AggregateSO();
		so.setFrom(DateCalculator.getBegin(queryDefinition.getStartDate(), queryDefinition.getTimeDimension()));
		so.setTo(DateCalculator.getEnd(queryDefinition.getEndDate(), queryDefinition.getTimeDimension()));
		so.setName(queryDefinition.getName());
		so.setViewBy(queryDefinition.getViewBy());
		so.setUserId(queryDefinition.getUser());
		so.setTag(queryDefinition.getTag());
		so.setShop(queryDefinition.getShop());
		so.setExcludedDimensions(queryDefinition.getExcludedDimensions());
		
		//viewBy is not added to queryDefinition.dimensions() if it's the root dimension
		List<Dimension> constraints = queryDefinition.getDimensions();
		if (queryDefinition.getViewBy() != null) {
			boolean hasViewByCondition = false;
			String viewByRoot = queryDefinition.getViewBy().getRootDimension();
			if(viewByRoot == null) viewByRoot = queryDefinition.getViewBy().getEncodedKey();
			for (Dimension dimension : queryDefinition.getDimensions()) {
				String dimRoot = dimension.getRootDimension();
				if(dimRoot == null) dimRoot = dimension.getEncodedKey();
				if (dimRoot.equals(viewByRoot)) {
					hasViewByCondition = true;
					so.setViewBy(dimension);
					break;
				}
			}
			if (!hasViewByCondition) {
				constraints.add(queryDefinition.getViewBy());
			}
		}
		
		for(Dimension dimension : constraints) {
//			if (DimensionUtil.isCategory(dimension)) {
//				so.setCategory(dimension.getEncodedKey());
//				so.setCategoryPosition(dimension.getPosition());
//			} else if(!StringUtil.isEmpty(dimension.getParent())) {
			if(!StringUtil.isEmpty(dimension.getParent()))
				so.addDimension(dimension);
//			}
		}

		return so;
	}
	
}
